from fastapi import APIRouter, UploadFile, File, HTTPException
import os
from openai import OpenAI
from typing import Annotated,List, Optional
import base64

from bisheng.database.base import session_getter
from sqlmodel import select
from bisheng.api.v1.schemas import resp_200
#
from bisheng.api.sh_api.service.sh_service import ShService
from bisheng.api.sh_api.model.user_chat_relation import UserChat
from bisheng.api.v1.schemas import ChatList

router = APIRouter(prefix='/tool', tags=['OpenAPI', 'sh'])



# 初始化OpenAI客户端
client = OpenAI(
    api_key = "sk-aaae3bece8294f8ea9270d3f0d0058d3",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)


@router.post("/get_pic_info", status_code=200)
async def get_pic_info_by_model(
        file: Annotated[UploadFile, File(description="上传的图片文件")]
):
    """
    图片内容分析接口
    参数：
    - file: 上传的图片文件（支持jpg/png/gif）

    返回：
    - 图片分析结果字符串 或 空字符串
    """

    reasoning_content = ""  # 定义完整思考过程
    answer_content = ""  # 定义完整回复
    is_answering = False  # 判断是否结束思考过程并开始回复

    # 1. 校验文件类型
    allowed_types = ["image/jpeg", "image/png", "image/gif"]
    if file.content_type not in allowed_types:
        return ""

    try:
        # 2. 读取文件内容
        file_content = await file.read()
        base64_image = base64.b64encode(file_content).decode("utf-8")  # 修复base64编码

        # 3. 调用OpenAI API分析图片
        # 创建聊天完成请求
        completion = client.chat.completions.create(
            model="qwen-vl-plus",  # 此处以 qwen-vl-plus 为例，可按需更换模型名称
            messages=[
                {
                    "role": "system",
                    "content": "请用中文帮我把这张图片进行描述，这张图是对孩子语言能力的概括，我需要客观的知道孩子的语言能力" +
                               "请注意不要回复图片以外的信息。尤其是请注意等描述语言。"
                },
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": f"data:{file.content_type};base64,{base64_image}"  # 动态匹配图片类型
                            }
                        }
                    ]
                }
            ],
            stream=True,
            # 解除以下注释会在最后一个chunk返回Token使用量
            # stream_options={
            #     "include_usage": True
            # }
        )
        print("\n" + "=" * 20 + "思考过程" + "=" * 20 + "\n")

        for chunk in completion:
            # 如果chunk.choices为空，则打印usage
            if not chunk.choices:
                print("\nUsage:")
                print(chunk.usage)
            else:
                delta = chunk.choices[0].delta
                # 打印思考过程
                if hasattr(delta, 'reasoning_content') and delta.reasoning_content != None:
                    print(delta.reasoning_content, end='', flush=True)
                    reasoning_content += delta.reasoning_content
                else:
                    # 开始回复
                    if delta.content != "" and is_answering is False:
                        print("\n" + "=" * 20 + "完整回复" + "=" * 20 + "\n")
                        is_answering = True
                    # 打印回复过程
                    print(delta.content, end='', flush=True)
                    answer_content += delta.content

        print("=" * 20 + "完整思考过程" + "=" * 20 + "\n")
        print(reasoning_content)
        print("=" * 20 + "完整回复" + "=" * 20 + "\n")
        print(answer_content)

        # 4. 提取并返回分析结果
        return answer_content

    except Exception as e:
        # 异常处理
        raise HTTPException(
            status_code=500,
            detail=f"图片分析失败: {str(e)}"
        )


def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")


@router.get('/chat/history',status_code=200)
def get_chatmessage(chat_id: str,
                    category_list: Optional[list] = None,
                    page_size: Optional[int] = 20):
    if not chat_id:
        return {'code': 500, 'message': 'chat_id 必传参数'}
    return resp_200(ShService().get_user_chat_by_chat_id(chat_id,category_list,page_size))
#
@router.get('/chat/list',status_code=200)
def get_chat_by_user_id(user_id: str,
                        page_size: Optional[int] = 10):
    if not user_id:
        return {'code': 500, 'message': 'user_id 必传参数'}
    return resp_200(ShService().get_user_chat(user_id,page_size))
